package com.ruoyi.resume.controller;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.resume.enums.TaskType;
import com.ruoyi.resume.service.TaskProcessorService;
import com.ruoyi.resume.task.Task;
import com.ruoyi.resume.task.TaskQueue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/tasks")
public class TaskController {

    @Autowired
    private TaskQueue taskQueue;

    @Autowired
    private TaskProcessorService taskProcessorService;

    @PostMapping("/add")
    @Anonymous
    public ResponseEntity<String> addTask(@RequestParam TaskType type, @RequestParam Integer param) {
        Task task = new Task(type, param);
        if (taskQueue.addTask(task)) {
            return ResponseEntity.ok("任务已添加，类型：" + type + "，参数：" + param);
        } else {
            return ResponseEntity.status(HttpStatus.CONFLICT).body("任务已存在，类型：" + type + "，参数：" + param);
        }
    }

    /**
     * 手动执行所有任务
     */
    @PostMapping("/executeAll")
    @Anonymous
    public ResponseEntity<String> executeAllTasks() {
        try {
            taskProcessorService.processAllTasks(taskQueue); // 将任务队列传递到服务层处理
            return ResponseEntity.ok("所有任务已手动执行完成");
        } catch (IllegalArgumentException e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("任务执行失败: " + e.getMessage());
        }
    }
}
